package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.dto.OrderDto;
import com.hdax.dm.entity.order.DmOrder;
import com.hdax.dm.mappers.OrderMapper;
import com.hdax.dm.mapstruct.OrderDtoMapper;
import com.hdax.dm.service.OrderService;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@Service
public class OrderSImpl extends ServiceImpl<OrderMapper, DmOrder> implements OrderService {

    @Autowired
    private OrderDtoMapper orderDtoMapper;

    @Override
    public CommonResponse<List<OrderDto>> queryorderlist(Map<String,Object> map,Integer uid) {
        String keyword= (String) map.get("keyword");
        Integer orderTime= (Integer) map.get("orderTime");

        QueryWrapper<DmOrder> wrapper=new QueryWrapper();
        wrapper.eq("userId",3);
        if(map.get("orderType")!=""){
            wrapper.eq("orderType",map.get("orderType").toString());
        }
        if (keyword!=null && keyword!=""){
            wrapper.like("itemName",keyword);
        }

        LocalDateTime now = LocalDateTime.now();
        if (orderTime==1){//一年内
            now=now.minus(1, ChronoUnit.YEARS);
            wrapper.between("createdTime",now,LocalDateTime.now());
        }else if(orderTime==2){

            //近3个月
            now=now.minus(3, ChronoUnit.MONTHS);
            wrapper.between("createdTime",now,LocalDateTime.now());
        }
        wrapper.last("order by createdTime desc");
        return ResponseUtil.returnSuccess(orderDtoMapper.toTargets(list(wrapper)));
    }

    @Override
    public Integer OrderAdd(DmOrder order) {
        order.setCreatedTime(LocalDateTime.now());
        return baseMapper.insert(order);
    }

    @Override
    public DmOrder orderOne(String orderNo) {
        QueryWrapper<DmOrder> wrapper=new QueryWrapper();
        wrapper.eq("orderNo",orderNo);
        return getOne(wrapper);
    }

    @Override
    public Integer orderDel(String orderNo) {
        QueryWrapper<DmOrder> wrapper=new QueryWrapper();
        wrapper.eq("orderNo",orderNo);
        return baseMapper.delete(wrapper);
    }

    @Override
    public Boolean orderUpdate(Long orderType,String orderNo) {
        DmOrder order=new DmOrder();
        QueryWrapper<DmOrder> wrapper=new QueryWrapper();
        wrapper.eq("orderNo",orderNo);
        order.setOrderType(orderType);
        return update(order,wrapper);
    }
}
